import { NotFound } from 'http-errors'
import Attachment from '@/database/models/attachment'
import User from '@/database/models/user'
import { client } from '@/utils/aliyun'

const getAttachments = async (query: Query) => {
  const pageNum = Math.abs(Number(query.pageNum)) || 1
  const pageSize = Math.abs(Number(query.pageSize)) || 10
  const offset = (pageNum - 1) * pageSize
  const { count, rows } = await Attachment.findAndCountAll({
    attributes: { exclude: ['userId'] },
    include: {
      model: User,
      as: 'user',
      attributes: ['id', 'username', 'avatar'],
    },
    order: [['id', 'DESC']],
    limit: pageSize,
    offset,
  })
  return {
    attachments: rows,
    pagination: {
      total: count,
      pageNum,
      pageSize,
    },
  }
}

const createAttachment = async (userId: number, file: Express.Multer.File) => {
  const { path, filename, url } = file
  // 记录附件信息
  await Attachment.create({
    ...file,
    userId: userId,
    url: url as string,
    fullpath: path + '/' + filename,
  })
}

const deleteAttachment = async function (id: number) {
  const attachment = await getAttachment(id)
  await client.delete(attachment.fullpath)
  await attachment.destroy()
}

/**
 * 公共方法：查询当前附件
 */
async function getAttachment(id: number) {
  const attachment = await Attachment.findByPk(id, {
    // include: {
    //   model: User,
    //   as: 'user',
    //   attributes: ['id', 'username', 'avatar'],
    // },
  })
  if (!attachment) {
    throw new NotFound(`ID:${id}的附件未找到。`)
  }
  return attachment
}

export default {
  getAttachments,
  createAttachment,
  deleteAttachment,
}
